<?php

namespace app\admin\controller;

use support\Request;
use support\think\Db;
use think\Exception;

class AdminLogController extends BaseController
{
    public function initialize()
    {
        parent::initialize();

        // 当前model
        $this->model = 'AdminLog';
        //$this->indexView = 'adminlog:list';
        //$this->primaryKey = 'log_id';

        $this->defaultOrder = 'a.created_at DESC';
    }

    /**
     * List
     */
    public function index(Request $request)
    {
        $param = $request->all();

        if ($request->isAjax()) {
            $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
            $model = new $className;

            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];
            // 排序条件
            $order = '';

            $where = $this->getFilterWhere($request);
            if ($this->defaultWhere) {
                $where = array_merge($this->defaultWhere, $where);
            }
            if ($this->defaultOrder) {
                $order = $this->defaultOrder;
            }
            $fields = 'a.*, b.name';
            $data = $className::alias('a')
                ->join('admins b', 'b.id = a.created_id')
                ->where($where)
                ->field($fields)
                ->limit($start, $length)
                ->order($order)
                ->select();
            $count = $className::alias('a')->join('admins b', 'b.id = a.created_id')->where($where)->count();
            if ($data) {
                // 处理列表数据
                foreach ($data as $item) {
                    //$item = $model->formatItem($item);
                    $item['username'] = '账号: ' . $item['name'];
                }
            }

            $result = [
                'code' => '0',
                'msg' => '请求成功',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return parent::index($request);
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['range_date']) && $param['range_date']) {
            $rangeDate = explode(' ~ ', $param['range_date']);
            $startTime = strtotime($rangeDate[0]);
            $endTime = strtotime($rangeDate[1]);
            $where[] = ['a.created_at', '>=', $startTime];
            $where[] = ['a.created_at', '<=', $endTime];
        }

        return $where;
    }
}